from django.http import HttpResponse
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response

from google.appengine.api import users

from models import *
from google.appengine.ext.db.djangoforms import ModelForm


class AddressForm(ModelForm):
    class Meta:
        model = Address
        exclude = ("user")
        
        
def address(request):

    if not users.get_current_user():
        return HttpResponseRedirect(users.create_login_url("/address"));

    currentUser = users.get_current_user()
    addressOfCurrentUser = Address.all().filter("user = ", currentUser).get()

    if request.POST:
        if not addressOfCurrentUser:
            # assign dummy values to required fields
            addressOfCurrentUser = Address(user = users.get_current_user(), name = "#", addressLine1 = "#", addressLine2 = "#",zip = "#", city = "#", country ="#" )
        form = AddressForm(request.POST, instance=addressOfCurrentUser)
    else:
        if addressOfCurrentUser:
            form = AddressForm(instance=addressOfCurrentUser)
        else:
            form = AddressForm(user = users.get_current_user())

    if form.is_valid():
        address = form.save()
        return HttpResponseRedirect('/profile-was-saved')

    return render_to_response('address.html', locals())
